package com.wyz.note.project.auth.core.config.security;

import cn.hutool.core.bean.BeanUtil;
import com.wyz.note.project.auth.common.constant.AuthConstant;
import com.wyz.note.project.auth.common.enums.RedisKeyEnum;
import com.wyz.note.project.auth.common.utils.ContextUtil;
import com.wyz.note.project.auth.common.utils.RedisUtil;
import com.wyz.note.project.auth.common.utils.SpringUtil;
import com.wyz.note.project.auth.common.vo.base.MenuPermissionInfo;
import com.wyz.note.project.auth.domain.pojo.Role;
import com.wyz.note.project.auth.domain.service.PermissionService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.PathContainer;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.pattern.PathPatternParser;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 自定义的Metadata，通过当前请求地址，获取该地址所需要的角色 权限查询器
 * @Author: wei yz
 * @Date: 2022/6/18 15:31
 */
public class NoteSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private static final Logger log = LoggerFactory.getLogger(NoteSecurityMetadataSource.class);

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PermissionService permissionService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        log.info("==> 进入权限查询器：{}", object);
        // object 中包含用户请求的 request 信息
        HttpServletRequest request = ((FilterInvocation) object).getRequest();
        // 提取出当前的uri
        String requestURI = request.getRequestURI();
        log.info("==> 当前登录的URI：{}", requestURI);
        if (BeanUtil.isEmpty(redisUtil)) {
            redisUtil = SpringUtil.getBean(RedisUtil.class);
        }
        // 查询redis获取所有菜单信息
        List<MenuPermissionInfo> permissionInfoList = (List<MenuPermissionInfo>) redisUtil.get(RedisKeyEnum.MENU_PERMISSION.getKey());
        // 不存在则查询数据库
        if (CollectionUtils.isEmpty(permissionInfoList)) {
            permissionInfoList = permissionService.getAllMenuInfo();
            redisUtil.set(RedisKeyEnum.MENU_PERMISSION.getKey(), permissionInfoList);
        }
        log.info("==> 查询Redis获取菜单信息：{}", permissionInfoList);
        for (MenuPermissionInfo menu : permissionInfoList) {
            log.info("==> 匹配菜单规则：{} <==> {}", menu.getUrl(), requestURI);
            // 匹配规则正确
            if (new PathPatternParser().parse(requestURI).matches(PathContainer.parsePath(menu.getUrl())) && !CollectionUtils.isEmpty(menu.getRoles())) {
                String[] roleCodes = menu.getRoles().stream().map(Role::getCode).toArray(String[]::new);
                log.info("==> 角色编码数组：{}", roleCodes);
                return SecurityConfig.createList(roleCodes);
            }
        }

        log.error("==> 菜单为空，没有权限<==");
        return SecurityConfig.createList(AuthConstant.ROLE_LOGIN);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

}
